clear all
close all

%  =======================================================================================================================================================
% 
%  Code Description: 
%  This codefile generates results in section 3 and internet appendix A.
% 
%  =======================================================================================================================================================
% 
%  Major output:
%  - Figure 4: Cross-fund holdings and fund returns.
%  - Figure 5: Cross-fund holdings and portfolio overlap.
%  - Figure IA.1: How large is the German fund sector?
%  =======================================================================================================================================================
% 
%  General disclaimer:
%  This file directory produces replication code for "Connected Funds". 
%  Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources, 
%  we have included pseudo data to show how the raw data are formatted. 
%  Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
% 
%  =======================================================================================================================================================


%% Set project directory

projectPath = 'C:\ConnectedFunds_Codebase\'

% Add functions folders
addpath(strcat(projectPath, 'Code\matlab_functions'));

load(strcat(projectPath, 'Data\CrossholdingsMatter\CrossHoldingsMatter_OverTime.mat'));


%  =================================================================== Figure IA.1: How large is the German fund sector? ===================================================================================


dates = datenum(string(umonth),'yyyymm');

close
plot(dates,10^-12*1000*Results_TotalAssets,'k-',dates,10^-12*1000*Results_TotalAssetsHat,'r-');
datetick('x','yyyy'); axis tight; grid on; xtickangle(45);
xlabel('Year');
ylabel('Assets under management (in EUR tn)'); 
legend('Reported','After look-through (Eq. (IA.5))','location','NorthWest');
saveas(gcf, strcat(projectPath, 'Paper\Figures\FigIA1_How large is the German fund sector.png'),'png');


%  =================================================================== Figure 5: Cross-fund holdings and portfolio overlap. ===================================================================================


close
plot(dates,[Results_OverlapPolk(:,1) Results_OverlapPolkHat(:,1)])
datetick('x','yyyy'); grid on;
ylabel('Portfolio overlap'); xlabel('Year'); xtickangle(45)
legend('Reported','After look-through','location','East');
saveas(gcf, strcat(projectPath, 'Paper\Figures\Fig5_Cross-fund holdings and portfolio overlap.png'),'png');


%  =================================================================== Figure 4: Cross-fund holdings and fund returns. ===================================================================================


load(strcat(projectPath, 'Data\IFS\IFS_All_CleanData.mat'), 'IFS_All');

ufund   = unique(IFS_All.ISIN);
[~,idx] = ismember(IFS_All.ISIN,ufund);
spezial = accumarray(idx,IFS_All.SPEZIAL,[length(ufund) 1],@max);
artmittel = accumarray(idx,IFS_All.artmittel,[length(ufund) 1],@max);

[~,idx]                 = ismember(Results_RE1_RE0.ISIN,ufund);
Results_RE1_RE0.SPEZIAL = spezial(idx);
Results_RE1_RE0.artmittel = artmittel(idx);
clear idx spezial ufund IFS_All;

dates = datenum(string(umonth), 'yyyymm');

MeanR = zeros(length(umonth),3);
MeanR_Artmittel = zeros(length(umonth),4);

WMeanR = zeros(length(umonth),3);
WMeanR_Artmittel = zeros(length(umonth),4);

for t = 2:length(umonth)

    % Mean 
    a = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t)));
    b = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.SPEZIAL == 0));
    c = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.SPEZIAL == 1));
    
    MeanR(t,:) = [a b c];
    
    a = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.artmittel == 1));
    b = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.artmittel == 2));
    c = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.artmittel == 3));
    d = nanmean(Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.artmittel == 7));
    
    MeanR_Artmittel(t,:) = [a b c d];
    
    % TNA-weighted mean
    tna = Results_RE1_RE0.totalassets(Results_RE1_RE0.DATUM == umonth(t));
    r =   Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t));
    a =   nansum(tna.*r)./nansum(tna);
    
    tna = Results_RE1_RE0.totalassets(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.SPEZIAL == 0);
    r =   Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.SPEZIAL == 0);
    b =   nansum(tna.*r)./nansum(tna);
    
    tna = Results_RE1_RE0.totalassets(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.SPEZIAL == 1);
    r =   Results_RE1_RE0.RE1(Results_RE1_RE0.DATUM == umonth(t) & Results_RE1_RE0.SPEZIAL == 1);
    c =   nansum(tna.*r)./nansum(tna);
    
    WMeanR(t,:) = [a b c];
    
    clear a b c tna r;
end

% Drop FoFs
Results_RE1_RE0(Results_RE1_RE0.artmittel == 7, :) = [];

% Add VIX
% (Source: https://www.cboe.com/tradable_products/vix/vix_historical_data/)
VIX = readtable(strcat(projectPath, 'Data\VIX\vix_monthly.csv'));
VIX.delta_VIX               = NaN(height(VIX),1);
VIX.delta_VIX(2:end)        = diff(VIX.vixclose);
VIX.delta_log_VIX           = NaN(height(VIX),1);
VIX.delta_log_VIX(2:end)    = diff(log(VIX.vixclose));

[~,idxWhereMonth] = ismember(Results_RE1_RE0.DATUM,VIX.datum);

Results_RE1_RE0.VIX(idxWhereMonth>0)        = VIX.vixclose(idxWhereMonth(idxWhereMonth>0));    
Results_RE1_RE0.Delta_VIX(idxWhereMonth>0)  = VIX.delta_VIX(idxWhereMonth(idxWhereMonth>0));
vix                                         = VIX.vixclose(VIX.datum>=umonth(1) & VIX.datum <=umonth(end));
delta_vix                                   = VIX.delta_VIX(VIX.datum>=umonth(1) & VIX.datum <=umonth(end));
clear idx* VIX;

high_vix        = quantile(vix,0.8);
high_delta_vix  = quantile(delta_vix,0.8);

low_vix         = quantile(vix,0.2);
low_delta_vix   = quantile(delta_vix,0.2);

Results_RE1_RE0.High_VIX                                    = zeros(height(Results_RE1_RE0),1);
Results_RE1_RE0.High_VIX(vix > high_vix)                    = 1;
Results_RE1_RE0.High_Delta_VIX                              = zeros(height(Results_RE1_RE0),1);
Results_RE1_RE0.High_Delta_VIX(delta_vix > high_delta_vix)  = 1;

Results_RE1_RE0.Low_VIX                                     = zeros(height(Results_RE1_RE0),1);
Results_RE1_RE0.Low_VIX(vix < low_vix)                      = 1;
Results_RE1_RE0.Low_Delta_VIX                               = zeros(height(Results_RE1_RE0),1);
Results_RE1_RE0.Low_Delta_VIX(delta_vix < low_delta_vix)    = 1;


%  =================================================================== Plot figure 4: Cross-fund holdings and fund returns. ===================================================================================


% Full sample plot - only funds with some fund shares in their portfolio
close
ksdensity(Results_RE1_RE0.RE1(Results_RE1_RE0.w_fund>0),(-5:0.01:5)); 
hold on; 
ksdensity(Results_RE1_RE0.RE0(Results_RE1_RE0.w_fund>0),(-5:0.01:5)); hold off;
axis tight; grid on;
legend('$R$','$R^{adj.}$','interpreter','latex','location','Best');
xlabel('Return (in percent)'); ylabel('Density'); title('Full sample')
saveas(gcf, strcat(projectPath, 'Paper\Figures\Fig4T_Cross-fund holdings and fund returns.png'),'png');


% Split: high versus low delta_vix

% 1. low delta_vix
close
ksdensity(Results_RE1_RE0.RE1(Results_RE1_RE0.w_fund>0 & Results_RE1_RE0.Delta_VIX<low_delta_vix),(-5:0.01:5)); 
hold on; 
ksdensity(Results_RE1_RE0.RE0(Results_RE1_RE0.w_fund>0  & Results_RE1_RE0.Delta_VIX<low_delta_vix),(-5:0.01:5)); hold off;
axis tight; grid on;
legend('$R$','$R^{adj.}$','interpreter','latex','location','Best');
xlabel('Return (in percent)'); ylabel('Density'); title('Low Delta VIX')
saveas(gcf, strcat(projectPath, 'Paper\Figures\Fig4R_Cross-fund holdings and fund returns.png'),'png');

% 2. high delta_vix
close
ksdensity(Results_RE1_RE0.RE1(Results_RE1_RE0.w_fund>0 & Results_RE1_RE0.Delta_VIX>=high_delta_vix),(-5:0.01:5)); 
hold on; 
ksdensity(Results_RE1_RE0.RE0(Results_RE1_RE0.w_fund>0  & Results_RE1_RE0.Delta_VIX>=high_delta_vix),(-5:0.01:5)); hold off;
xlim([-5,5])
axis tight; grid on;
legend('$R$','$R^{adj.}$','interpreter','latex','location','Best');
xlabel('Return (in percent)'); ylabel('Density'); title('High Delta VIX')
saveas(gcf, strcat(projectPath, 'Paper\Figures\Fig4L_Cross-fund holdings and fund returns.png'),'png');